import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileConvert {
	File file = null;
	String i18n_ko = null;
	String temp = null;
	String regex = "(\"|'|>)([\uAC00-\uD7A3 \\n.!\\w\\d\\p{javaWhitespace}/?▲▼]+)(\"|'|<)";
	Pattern pattern = null;
	ConvertWriter convertLog = null;
	ConvertWriter i18n_koFile = null;
	Matcher matcher;
	int lineNum = 1;
	int searchCnt = 0;
	StringBuffer sb = new StringBuffer();
	StringBuffer sbTemp = new StringBuffer();
	
	// 주석인지 체크
	boolean isComment = false;
	StringBuffer CommentStr = new StringBuffer();;

	public FileConvert(File file, ConvertWriter convertedLog) {
		convertLog = convertedLog;
		FileConvert(file);
	}
	
	public void FileConvert(File file) {
		pattern = Pattern.compile(regex);

		this.file = file;
		this.i18n_ko = file.getParent() + System.getProperty("file.separator")
				+ "i18n_ko.js";

		this.temp = file.getAbsoluteFile() + "_temp";

		try {
			fileRead(file);
		} catch (IOException e) {
			e.printStackTrace();
		}

		fileParse();

		fileWrite();
	}


	private void fileRead(File file) throws IOException {

		System.err.println(file.getAbsolutePath() + " 읽기 시작");
	}

	private void fileParse() {
		try {
			FileReader fr = new FileReader(file);
			BufferedReader buffer = new BufferedReader(fr);

			String s;

			sb.append("/* ").append(file.getAbsolutePath()).append(" */")
					.append("\n");

			while ((s = buffer.readLine()) != null) {


				// 주석 시작인지 체크
				Pattern commentPatten = Pattern.compile("[ |	]/[*]+");
				Matcher commentMatcher = commentPatten.matcher(s);
				
				if(commentMatcher.find()) {
					isComment = true;
					CommentStr.append(s.substring(commentMatcher.start()));
					s = s.substring(0, commentMatcher.start());
				}
				
				// 주석 종료인지 체크
				commentPatten = Pattern.compile("[*]/");
				commentMatcher = commentPatten.matcher(s);
				
				if(commentMatcher.find()) {
					isComment = false;
					CommentStr.append(s.substring(0, commentMatcher.end()));
					s = s.substring(commentMatcher.end());
				}
				
				
				// 한줄 주석인지 체크
				commentPatten = Pattern.compile("[ |	]?//.+$");
				commentMatcher = commentPatten.matcher(s);
				
				if(commentMatcher.find() && !isComment) {
					CommentStr.append(s.substring(commentMatcher.start(), commentMatcher.end()));
					s = s.substring(0, commentMatcher.start());
					System.err.print("한줄 주석 Line " + lineNum + " : " + s);
					System.err.println(" ========> " + CommentStr.toString());
				}
				
				if(!isComment) {
					// 한글이 있는지 체크
					Pattern tempPattern = Pattern.compile("(?:[\uAC00-\uD7A3]+)");
					Matcher matcherTemp = tempPattern.matcher(s);
					if (matcherTemp.find()) {
						System.out.println("Line " + lineNum + " : " + s);
						findString(s);
						sbTemp.append(CommentStr.toString()).append("\n");
						CommentStr = new StringBuffer();
					} else {
						sbTemp.append(s).append(CommentStr.toString()).append("\n");
						CommentStr = new StringBuffer();
					}
				} else {
					CommentStr.append(s).append("\n");
				}

				lineNum++;
					
			}

			sb.append("\n\n");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void findString(String str) {
		int start = 0;
		int end = 0;
		String inputStr = str;

		// 한글을 감싸고 있는 부분 찾기
		Pattern startPattern = Pattern.compile("(\"|'|>)+");
		Matcher startMatcher = startPattern.matcher(str);
		if (startMatcher.find()) {
			String startMatchString = startMatcher.group();

			// 시작된 패턴과 같은 쌍 찾기 패턴
			String endMatchRegex = "";
			if (startMatchString.equals("\"")) {
				endMatchRegex = "([\\\\" + startMatchString + "]{1})";
			} else if (startMatchString.equals(">")) {
				endMatchRegex = "([<]{1})";
			} else if (startMatchString.equals("'")) {
				endMatchRegex = "([" + startMatchString + "]{1})";
			}

			start = startMatcher.start() + 1;

			// 한글을 감싸고 있는 부분 찾기
			Pattern endPattern = Pattern.compile(endMatchRegex);

			sbTemp.append(str.substring(0, start));

			Matcher endMatcher = endPattern.matcher(str.substring(start));

			if (endMatcher.find()) {
				end = start + endMatcher.start();

				String findLast = str.substring(start, end);

				// 찾은 부분에 한글이 포함되어 있는지 체크
				Pattern korPattern = Pattern.compile("(?:[\uAC00-\uD7A3]+)");
				Matcher koMatcher = korPattern.matcher(findLast);

				if (koMatcher.find()) {
					// 찾은 부분에 태그가 포함되어 있는지 체크
					Pattern tagPattern = Pattern.compile("(?:[>|<]+)");
					Matcher tagMatcher = tagPattern.matcher(findLast);
					if (tagMatcher.find()) {
						findString(findLast);
					} else {
						sb.append("// Line ").append(lineNum).append(" : ")
								.append(findLast).append("\n");
						sb.append("i18nClass.add('").append(file.getName())
								.append("_").append(lineNum).append("_")
								.append(searchCnt).append("', '")
								.append(findLast).append("');").append("\n");

						// sbTemp.append(findLast);
						if (!startMatchString.equals(">")) {
							sbTemp.append(startMatchString).append(" + ");
							sbTemp.append("i18nClass.getText(\"")
									.append(file.getName()).append("_")
									.append(lineNum).append("_")
									.append(searchCnt).append("\")");
							sbTemp.append(" + ").append(startMatchString);
						} else {
							sbTemp.append("'").append(" + ");
							sbTemp.append("i18nClass.getText(\"")
									.append(file.getName()).append("_")
									.append(lineNum).append("_")
									.append(searchCnt).append("\")");
							sbTemp.append(" + ").append("'");
						}

						searchCnt++;
					}
				} else {
					sbTemp.append(findLast);
				}

				// 남은 부분에 한글이 있는지 체크
				findString(str.substring(end));
			} else {
				sbTemp.append(str.substring(start));
			}
		} else {
			sbTemp.append(str);
		}
	}

	private void fileWrite() {
		if (searchCnt > 0) {
			i18n_koFile = new ConvertWriter(this.i18n_ko);
			i18n_koFile.log(sb.toString());
			System.err.println(i18n_koFile.file.getAbsolutePath() + " 생성");

			ConvertWriter tempFile = new ConvertWriter(this.temp);
			tempFile.log(sbTemp.toString());
			System.err.println(tempFile.file.getAbsolutePath() + " 생성");

			// 코드 수정된 파일로 변경
			this.file.delete();
			try {
				DirHelper.copyDirectory(tempFile.file, this.file);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			System.err.println(convertLog.Fname + "에 기록");
			convertLog.log(sb.toString());
		}
	}

	public String toString() {
		return this.file.getAbsolutePath();
	}
}
